package com.traffic.api.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayCommerceTransportOfflinepayVirtualcardSendRequest;
import com.alipay.api.response.AlipayCommerceTransportOfflinepayVirtualcardSendResponse;
import com.traffic.api.bean.VirtualCardSyncRequest;
import com.traffic.api.entity.AlipayUser;
import com.traffic.api.entity.VirtualTransitCard;
import com.traffic.api.entity.VirtualTransitCardRetry;
import com.traffic.api.service.AlipayUserService;
import com.traffic.api.service.VirtualTransitCardRetryService;
import com.traffic.api.service.VirtualTransitCardService;
import com.traffic.api.util.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static com.traffic.api.util.GlobalUrl.*;

/**
 * Created by churcy on 2017/2/28.
 */
@Controller
public class AlipayVirtualCardController {

    private static final Logger LOG = LoggerFactory.getLogger(AlipayVirtualCardController.class);
    private static final List<String> testBizContent = new ArrayList<>();

    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 10, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3),
            new ThreadPoolExecutor.DiscardOldestPolicy());

    static {

        testBizContent.add(formatBizContent("ISSUE", "2088602245330764", "2017051920516781", "false", null));
        testBizContent.add(formatBizContent("ISSUE", "2088002233347736", "2017041413501440", "false", null));
        testBizContent.add(formatBizContent("ISSUE", "2088102042969212", "2017051114272913", "false", null));
        testBizContent.add(formatBizContent("ISSUE", "2088402784936021", "2017041316370986", "false", null));
        testBizContent.add(formatBizContent("ISSUE", "2088402107362849", "2017031015403697", "false", null));
    }

    @Autowired
    private VirtualTransitCardService virtualTransitCardService;

    @Autowired
    private AlipayUserService alipayUserService;

    @Autowired
    private VirtualTransitCardRetryService virtualTransitCardRetryService;

    public static final String VIRTUAL_TRANSIT_CARD_TYPE = "T0420100";

    /**
     * 虚拟电子公交卡 开卡
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/virtual/card/alipay/status", method = RequestMethod.POST)
    public Object changCardStatus(HttpServletRequest request) {
        VirtualTransitCard virtualTransitCard = new VirtualTransitCard();
        boolean isHaveCard = false;
        Map<String, Object> obj = new HashMap<>();
        String userId = request.getParameter("userId");
        String cardNo = DateUtils.format2String(new Date(), "MMddHHmmss") + RandomUtil.createVerificationCode(6);
        cardNo = AlipayUtils.checkCardCache(cardNo);
        LOG.info("生成的卡号为：" + cardNo);
        VirtualCardSyncRequest virtualCardSyncRequest = new VirtualCardSyncRequest();
        boolean isException = true;//调用支付宝接口是否存在异常标记位
        try {
            do {
                if (StringUtils.isAnyBlank(userId)) {
                    //请求参数错误
                    LOG.error("请求参数为空：" + "userId 的值为，" + userId);
                    obj = setResponse(null, "40001", "参数为空");
                    break;
                }

                //检查个人信息
                Map<String, Object> alipayUser = alipayUserService.getByUserId(userId);
                if (alipayUser == null || alipayUser.size() == 0) {
                    obj = setResponse(null, "40013", "用户不存在");
                    break;
                }

                List<Map<String, Object>> alipayUserCertNo = alipayUserService.getByCertNo((String) alipayUser.get("certNo"));
                //校验是否开卡
                boolean isCard = false;
                Map<String, Object> tempCard;
                if (alipayUserCertNo != null || alipayUserCertNo.size() != 0) {
                    for (Map<String, Object> temp : alipayUserCertNo) {
                        Map<String, Object> tempConditions = new HashMap<>();
                        tempConditions.put("userId", temp.get("userId"));
                        tempConditions.put("deleted", "FALSE");
                        tempConditions.put("result", "SUCCESS");
                        tempCard = virtualTransitCardService.checkCard(tempConditions);
                        if (tempCard != null) {
                            if (tempCard.size() != 0) {
                                isCard = true;
                            }
                        }
                    }
                    if (isCard) {
                        obj = setResponse(null, "40002", "支付宝账号已开通会员卡");
                        break;
                    }
                }


                //保存会员卡信息在本地
                virtualTransitCard = virtualTransitCardService.getByUserId(userId);
                //保存历史卡信息 用于错误回滚
                if (virtualTransitCard != null) {
                    virtualTransitCard.setDeleted("FALSE");
                    virtualTransitCard.setCardStatus("enabled");
                    cardNo = virtualTransitCard.getCardNo();
                    isHaveCard = true;
                } else {
                    virtualTransitCard = new VirtualTransitCard();
                    virtualTransitCard.setUserId(userId);
                    virtualTransitCard.setCardNo(cardNo);
                    virtualTransitCard.setCardStatus("enabled");
                    virtualTransitCard.setDeleted("FALSE");
                    virtualTransitCard.setCardType(VIRTUAL_TRANSIT_CARD_TYPE);

                }
                //同步支付宝数据
                String bizContent = null;
                //压测过滤
                if (userId.substring(0, 8).equals("TEST_UID")) {
                    Random random = new Random();
                    int flag = random.nextInt(5);
                    bizContent = testBizContent.get(flag);
                } else {
                    bizContent = formatBizContent("ISSUE", userId, cardNo, "false", null);
                }

                AlipayCommerceTransportOfflinepayVirtualcardSendResponse response = syncVirtualCardStatus(bizContent);
                Map<String, Object> result = checkAlipayResponse(response);
                isException = (boolean) result.get("flag");//是否存在异常标记
                obj = (Map<String, Object>) result.get("obj");

                virtualTransitCard.setCode(response.getCode());
                virtualTransitCard.setSubCode(response.getSubCode());
                virtualTransitCard.setSubMessage(response.getSubMsg());
                String localCardStatus = virtualTransitCard.getCardStatus();

                if (isException) {
                    virtualTransitCard.setCardStatus(localCardStatus);
                    virtualTransitCard.setResult("FAIL");
                    virtualTransitCard.setNeedRetry("TRUE");
                    virtualTransitCard.setErrorCode(response.getSubErrorCode());
                    virtualTransitCard.setErrorMessage(response.getErrorMessage());
                    if (isHaveCard) {
                        virtualTransitCardService.update(virtualTransitCard);
                    } else {
                        virtualTransitCardService.save(virtualTransitCard);
                    }
                    break;
                }
                virtualTransitCard.setNeedRetry("FALSE");
                virtualTransitCard.setResult("SUCCESS");
                long cardTime = new Date().getTime();
                if (isHaveCard) {
                    virtualTransitCardService.update(virtualTransitCard);
                } else {
                    virtualTransitCardService.save(virtualTransitCard);
                }
                String finalCardNo = cardNo;
               /* threadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            StringBuffer postEntity = new StringBuffer();
                            postEntity.append("key1Color=#000000");
                            postEntity.append("&key2Color=#000000");
                            postEntity.append("&key1Value=" + finalCardNo);
                            postEntity.append("&key2Value=" + DateUtils.format2String(new Date(), "yyyy-MM-dd HH:mm"));
                            postEntity.append("&templateId=" + MATCHER_FOLLOW_TEMPLATE_ID);
                            postEntity.append("&userId=" + userId);
                            postEntity.append("&headColor=#000000");
                            postEntity.append("&remarkColor=#000000");
                            postEntity.append("&remarkValue=" + URLEncoder.encode("【实时公交到站查询】就用——武汉电子公交卡", "UTF-8"));
                            postEntity.append("&firstColor=#000000");
                            postEntity.append("&firstValue=" + URLEncoder.encode("尊敬的会员您好，您已成功开通武汉电子公交卡", "UTF-8"));
                            String tempResponse = HttpUtil.httpPost(FOLLOW_SERVICE_WINDOW, null, postEntity.toString());
                        } catch (Exception e) {
                            LOG.info("匹配关注：异常");
                            e.printStackTrace();
                        }
                    }
                });*/
                //业务处理完成，返回数据
                Map<String, Object> data = new HashMap<>();
                data.put("cardNo", cardNo);
                data.put("userId", userId);
                data.put("successUrl", SUCCESS_OPEN_CARD_URL + "&cardNo=" + cardNo + "&firstOpened=true&scene=TRANSIT&subScene=420100");
                obj = setResponse(data, "20000", "请求成功");
                LOG.info("开卡流程结束，结果无异常");
            } while (false);

        } catch (AlipayApiException ali) {
            ali.printStackTrace();
            virtualTransitCard.setCode("90002");
            virtualTransitCard.setSubCode("AlipayClientException");
            virtualTransitCard.setSubMessage("");
            virtualTransitCard.setResult("FAIL");
            virtualTransitCard.setNeedRetry("TRUE");
            virtualTransitCard.setErrorCode(ali.getErrCode());
            if (isHaveCard) {
                virtualTransitCardService.update(virtualTransitCard);
            } else {
                virtualTransitCard.setCardNo(cardNo);
                virtualTransitCardService.save(virtualTransitCard);
            }
            obj = setResponse(null, "90002", "AlipayApiException");
        } catch (Exception e) {
            LOG.error("系统异常，请联系管理员！");
            virtualTransitCard.setCode("90001");
            virtualTransitCard.setSubCode("SYS_ERROR");
            virtualTransitCard.setSubMessage("");
            virtualTransitCard.setResult("FAIL");
            virtualTransitCard.setNeedRetry("TRUE");
            virtualTransitCard.setUserId(userId);
            if (isHaveCard) {
                virtualTransitCardService.update(virtualTransitCard);
            } else {
                virtualTransitCard.setCardNo(cardNo);
                virtualTransitCardService.save(virtualTransitCard);
            }

            obj = setResponse(null, "90001", "系统异常");
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * 审批后确认消卡
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/virtual/card/local/revoked", method = {RequestMethod.POST, RequestMethod.DELETE})
    public Object syncRevokedCardInfo(HttpServletRequest request) {
        //全局变量
        Map<String, Object> obj = new HashMap<>();
        String bizContent;//虚拟电子公交卡接口请求参数
        String code;//支付宝返回码
        boolean isException = true;//调用支付宝接口是否存在异常标记位
        AlipayCommerceTransportOfflinepayVirtualcardSendResponse response;
        Map<String, Object> data = new HashMap<>();

        //请求参数
        String userId = request.getParameter("userId");
        String cardNo = request.getParameter("cardNo");
        String action = request.getParameter("action");//enable disable revoke
        String disabledTips = request.getParameter("disabledTips");
        String batch = request.getParameter("disabledTips");
        try {
            do {
                if (StringUtils.isAnyBlank(userId, action)) {
                    //请求参数错误
                    LOG.error("请求参数为空：" + "userId 的值为，" + userId);
                    LOG.error("请求参数为空：" + "action 的值为，" + action);
                    obj = setResponse(null, "40001", "参数为空");
                    break;
                }
                //check 存在销卡时间
                Map<String, Object> conditions = new HashMap<>();
                conditions.put("userId", userId);
                conditions.put("cardNo", cardNo);
                conditions.put("deleted", "FALSE");
                List<VirtualTransitCard> virtualTransitCardList = virtualTransitCardService.findByConditions(conditions);

                System.out.println("消卡人信息：" + "userId:" + userId + " cardNo: " + cardNo);
                if (virtualTransitCardList == null || virtualTransitCardList.size() == 0) {
                    //卡不存在
                    obj = setResponse(null, "40005", "虚拟电子公交卡信息不存在");
                    LOG.warn("系统不存在该卡信息，请核对！");
                    break;
                }
                VirtualTransitCard virtualTransitCard = virtualTransitCardList.get(0);
                Map<String, Object> result;
                //获取修改前本地卡状态  用于支付宝接口调用异常 手动修复 本地状态为原状态
                String localCardStatus = virtualTransitCard.getCardStatus();
                String localDisabledTips = virtualTransitCard.getDisabledTips();
                Date localCheckEndTime = virtualTransitCard.getCheckEndTime();
                String localCardNo = virtualTransitCard.getCardNo();
                String localUserId = virtualTransitCard.getUserId();
                String localCardType = virtualTransitCard.getCardType();

                if (cardNo == null) {
                    cardNo = localCardNo;
                }

                //设置卡状态为注销，等待处理 默认五天
                virtualTransitCard.setCardStatus("revoked");
                Date checkEndTime = new Date(new Date().getTime() + 5 * 24 * 60 * 60 * 1000);
                virtualTransitCard.setCheckEndTime(checkEndTime);
                virtualTransitCard.setDisabledTips(disabledTips);
                virtualTransitCard.setDeleted("TRUE");
                virtualTransitCardService.update(virtualTransitCard);
                //
                isException = false;
                bizContent = formatBizContent("REVOKE", userId, cardNo, "true", disabledTips);
                response = syncVirtualCardStatus(bizContent);
                result = checkAlipayResponse(response);
                isException = (boolean) result.get("flag");//是否存在异常标记
                obj = (Map<String, Object>) result.get("obj");
                LOG.info("支付宝开卡接口返回码为：" + result.get("code"));
                LOG.info("支付宝开卡接口返回描述信息为：" + result.get("subMsg"));
                //更新数据
                if (!isException) {
                    virtualTransitCard.setResult(null);
                    //返回结果
                    data.put("cardNo", cardNo);
                    data.put("userId", userId);
                    obj = setResponse(data, "20000", "请求成功");
                } else {
                    //如果支付宝接口异常，手动 恢复本地数据
                    virtualTransitCard.setCardStatus(localCardStatus);
                    virtualTransitCard.setCheckEndTime(localCheckEndTime);
                    virtualTransitCard.setDisabledTips(localDisabledTips);
                    virtualTransitCard.setCardNo(localCardNo);
                    virtualTransitCard.setCardType(localCardType);
                    virtualTransitCard.setUserId(userId);
                    virtualTransitCard.setDeleted("FALSE");
                    virtualTransitCardService.update(virtualTransitCard);
                }
                break;

            }
            while (false);
        } catch (Exception e) {
            LOG.error("系统异常，请联系管理员！");
            obj = setResponse(null, "90001", "系统异常");
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * 虚拟电子公交卡 修改使用，禁用状态 ，注销
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/virtual/card/local/status", method = {RequestMethod.POST, RequestMethod.DELETE})
    public Object virtualCardModify(HttpServletRequest request) {
        //全局变量
        Map<String, Object> obj = new HashMap<>();
        String bizContent;//虚拟电子公交卡接口请求参数
        String code;//支付宝返回码
        boolean isException = true;//调用支付宝接口是否存在异常标记位
        AlipayCommerceTransportOfflinepayVirtualcardSendResponse response;
        Map<String, Object> data = new HashMap<>();

        //请求参数
        String userId = request.getParameter("userId");
        String cardNo = request.getParameter("cardNo");
        String action = request.getParameter("action");//enable disable revoke
        String disabledTips = request.getParameter("disabledTips");

        try {
            do {
                if (StringUtils.isAnyBlank(userId, action)) {
                    //请求参数错误
                    LOG.error("请求参数为空：" + "userId 的值为，" + userId);
                    LOG.error("请求参数为空：" + "action 的值为，" + action);
                    obj = setResponse(null, "40001", "参数为空");
                    break;
                }
                //check 存在销卡时间
                Map<String, Object> conditions = new HashMap<>();
                conditions.put("userId", userId);
                conditions.put("cardNo", cardNo);
                List<VirtualTransitCard> virtualTransitCardList = virtualTransitCardService.findByConditions(conditions);

                System.out.println("userId:" + userId + " cardNo: " + cardNo);
                if (virtualTransitCardList == null || virtualTransitCardList.size() == 0) {
                    //卡不存在
                    obj = setResponse(null, "40005", "虚拟电子公交卡信息不存在");
                    LOG.warn("系统不存在该卡信息，请核对！");
                    break;
                }
                VirtualTransitCard virtualTransitCard = virtualTransitCardList.get(0);
                Map<String, Object> result;
                //获取修改前本地卡状态  用于支付宝接口调用异常 手动修复 本地状态为原状态
                String localCardStatus = virtualTransitCard.getCardStatus();
                String localDisabledTips = virtualTransitCard.getDisabledTips();
                Date localCheckEndTime = virtualTransitCard.getCheckEndTime();
                String localCardNo = virtualTransitCard.getCardNo();
                String localUserId = virtualTransitCard.getUserId();
                String localCardType = virtualTransitCard.getCardType();
                if (cardNo == null) {
                    cardNo = localCardNo;
                }
                if (StringUtils.isNotBlank(disabledTips)) {
                    disabledTips = URLDecoder.decode(disabledTips, UTF_8);
                }

                switch (action) {
                    case "revoke":
                        //设置卡状态为注销，等待处理 默认五天
                        virtualTransitCard.setCardStatus("revoked");
                        Date checkEndTime = new Date(new Date().getTime() + 5 * 24 * 60 * 60 * 1000);
                        virtualTransitCard.setCheckEndTime(checkEndTime);
                        virtualTransitCard.setDisabledTips(disabledTips);
                        virtualTransitCardService.update(virtualTransitCard);
                        isException = false;
                        break;
                    case "disable":
                        virtualTransitCard.setCardStatus("disabled");
                        virtualTransitCard.setCheckEndTime(new Date(new Date().getTime() + 5 * 24 * 60 * 60 * 1000));
                        virtualTransitCard.setDisabledTips(disabledTips);
                        virtualTransitCardService.update(virtualTransitCard);
                        //同步更新支付宝数据
                        bizContent = formatBizContent("UPDATE", userId, cardNo, "true", disabledTips);
                        response = syncVirtualCardStatus(bizContent);
                        result = checkAlipayResponse(response);
                        isException = (boolean) result.get("flag");//是否存在异常标记
                        obj = (Map<String, Object>) result.get("obj");
                        LOG.info("支付宝开卡接口返回码为：" + result.get("code"));
                        LOG.info("支付宝开卡接口返回描述信息为：" + result.get("subMsg"));
                        if (isException) break;
                        break;
                    case "enable":
                        virtualTransitCard.setCardStatus("enabled");
                        virtualTransitCard.setDisabledTips(disabledTips);
                        virtualTransitCard.setCheckEndTime(null);
                        virtualTransitCardService.update(virtualTransitCard);
                        //同步更新支付宝数据
                        bizContent = formatBizContent("UPDATE", userId, cardNo, "false", disabledTips);
                        response = syncVirtualCardStatus(bizContent);
                        result = checkAlipayResponse(response);
                        isException = (boolean) result.get("flag");//是否存在异常标记
                        obj = (Map<String, Object>) result.get("obj");
                        LOG.info("支付宝开卡接口返回码为：" + result.get("code"));
                        LOG.info("支付宝开卡接口返回描述信息为：" + result.get("subMsg"));
                        if (isException) {
                            break;
                        }
                        break;
                    default:
                        isException = true;
                        break;

                }
                //更新数据
                if (!isException) {
                    //返回结果
                    data.put("cardNo", cardNo);
                    data.put("userId", userId);
                    obj = setResponse(data, "20000", "请求成功");
                } else {
                    //如果支付宝接口异常，手动 恢复本地数据
                    VirtualTransitCard localVirtualTransitCard = new VirtualTransitCard();
                    localVirtualTransitCard.setCardStatus(localCardStatus);
                    localVirtualTransitCard.setCheckEndTime(localCheckEndTime);
                    localVirtualTransitCard.setDisabledTips(localDisabledTips);
                    localVirtualTransitCard.setCardNo(localCardNo);
                    localVirtualTransitCard.setCardType(localCardType);
                    localVirtualTransitCard.setUserId(userId);
                    if (action == "revoke") {
                        virtualTransitCardService.save(virtualTransitCard);
                    } else {
                        virtualTransitCardService.update(virtualTransitCard);
                    }
                }
            }
            while (false);
        } catch (Exception e) {
            LOG.error("系统异常，请联系管理员！");
            obj = setResponse(null, "90001", "系统异常");
            e.printStackTrace();
        }
        return obj;
    }


    /**
     * 虚拟电子公交卡
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/virtual/card", method = RequestMethod.POST)
    public Object virtualCardInfo(HttpServletRequest request) {
        Map<String, Object> obj = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        String userId = request.getParameter("userId");
        String cardNo = request.getParameter("cardNo");

        try {
            do {
                System.out.println("查询卡状态：userId " + userId);
                if (StringUtils.isAnyBlank(userId)) {
                    //param error
                    obj = setResponse(null, "40001", "参数为空");
                    break;
                }
                //check 销卡时间
                Map<String, Object> conditions = new HashMap<>();
                conditions.put("userId", userId);
                if (StringUtils.isNotBlank(cardNo)) {
                    conditions.put("cardNo", cardNo);
                }
                List<VirtualTransitCard> virtualTransitCardList = virtualTransitCardService.findByConditions(conditions);

                if (virtualTransitCardList == null || virtualTransitCardList.size() == 0) {
                    //卡不存在
                    obj = setResponse(null, "40005", "虚拟电子公交卡信息不存在");
                    break;
                }
                //虚拟卡信息
                VirtualTransitCard virtualTransitCard = virtualTransitCardList.get(0);
                String cardStatus = virtualTransitCard.getCardStatus();
                String disabledTips = virtualTransitCard.getDisabledTips();
                switch (cardStatus) {
                    case "enabled":
                        //卡使用中
                        break;
                    case "disabled":
                        //卡禁用中
                        data.put("disabledTips", disabledTips);
                        data.put("checkEndTime", virtualTransitCard.getCheckEndTime());
                        break;
                    case "revoked":
                        //卡已消除
                        data.put("disabledTips", disabledTips);
                        data.put("checkEndTime", virtualTransitCard.getCheckEndTime());
                        break;
                    default:
                        break;
                }
                //返回结果
                data.put("cardStatus", cardStatus);
                data.put("cardNo", virtualTransitCard.getCardNo());
                data.put("userId", userId);

                obj = setResponse(data, "20000", "请求成功");
                System.out.println(obj);
            } while (false);
        } catch (Exception e) {
            LOG.error("系统异常，请联系管理员！");
            System.out.println("系统异常，请联系管理员！");
            obj = setResponse(null, "90001", "系统异常");
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * alipay卡操作
     *
     * @param bizContent
     * @return
     * @throws AlipayApiException
     */
    private AlipayCommerceTransportOfflinepayVirtualcardSendResponse syncVirtualCardStatus(String bizContent) throws AlipayApiException {
        AlipayClient alipayClient =
                new DefaultAlipayClient(ALIPAY_GATEWAY, APP_ID, APP_PRIVATE_KEY, "json", GlobalUrl.UTF_8, ALIPAY_PUBLIC_KEY, GlobalUrl.SIGN_TYPE_RSA2);
        AlipayCommerceTransportOfflinepayVirtualcardSendRequest virtualCardSendRequest = new AlipayCommerceTransportOfflinepayVirtualcardSendRequest();
        virtualCardSendRequest.setBizContent(bizContent);
        AlipayCommerceTransportOfflinepayVirtualcardSendResponse virtualCardSendResponse = alipayClient.execute(virtualCardSendRequest);

        return virtualCardSendResponse;
    }

    /**
     * 设置全局返回结果
     */
    private Map<String, Object> setResponse(Object data, String code, String msg) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> message = new HashMap<>();

        result.put("data", data);
        message.put("code", code);
        message.put("msg", msg);
        result.put("message", message);

        return result;

    }

    /**
     * 请求参数
     *
     * @param userId
     * @param cardNo
     * @param disabledTips
     * @return
     */
    private static String formatBizContent(String action, String userId, String cardNo, String isDisabled, String disabledTips) {
        String bizContent;
        VirtualCardSyncRequest virtualCardSyncRequest = new VirtualCardSyncRequest();
        virtualCardSyncRequest.setAction(action);
        virtualCardSyncRequest.setUser_id(userId);
        virtualCardSyncRequest.setLast_update_time(DateUtils.format2String(new Date(), "yyyy-MM-dd HH:mm:ss"));
        virtualCardSyncRequest.setCard_type(VIRTUAL_TRANSIT_CARD_TYPE);
        virtualCardSyncRequest.setCard_no(cardNo);
        virtualCardSyncRequest.setDisabled(isDisabled);
        virtualCardSyncRequest.setDisabled_tips(disabledTips);
        bizContent = JSON.toJSONString(virtualCardSyncRequest);
        return bizContent;
    }

    /**
     * 检查支付宝返回结果
     *
     * @param response
     * @return
     */
    private Map<String, Object> checkAlipayResponse(AlipayCommerceTransportOfflinepayVirtualcardSendResponse response) {
        String code;
        boolean flag = false;
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> obj = new HashMap<>();
        String jsonObject = JSON.toJSONString(response);
        do {
            if (!response.isSuccess()) {

                //请求支付宝接口失败
                obj = setResponse(null, "40003", "支付宝接口返回信息为：" + jsonObject);
                flag = true;
                break;
            }
            code = response.getCode();
            if (!code.equals("10000")) {
                switch (response.getSubCode()) {
                    case "ILLEGAL_PARAMS":
                        obj = setResponse(null, "40006", "支付宝接口返回信息为：" + jsonObject);
                        flag = true;
                        break;
                    case "UNKNOWN":
                        //支付宝接口出错
                        obj = setResponse(null, "40010", "支付宝接口返回信息为：" + jsonObject);
                        flag = true;
                        break;
                    case "FAIL":
                        if (response.getSubCode().equals("SYSTEM_ERROR")) {
                            //支付宝接口出错
                            obj = setResponse(null, "40011", "支付宝接口返回信息为：" + jsonObject);
                            flag = true;
                            break;
                        } else if (response.getSubCode().equals("USER_ALREDAY_HAS_CARD")) {
                            obj = setResponse(null, "20000", "支付宝接口返回信息为：" + jsonObject);
                            flag = false;
                            break;
                        } else {
                            //支付宝接口出错
                            obj = setResponse(null, "40012", "支付宝接口返回信息为：" + jsonObject);
                            flag = true;
                            break;
                        }
                    default:
                        //支付宝接口出错
                        obj = setResponse(null, "40012", "支付宝接口返回信息为：" + jsonObject);
                        flag = true;
                        break;
                }
            } else {
                obj = setResponse(null, "20000", "支付宝接口返回信息为：" + jsonObject);
                flag = false;
                break;
            }
        } while (false);
        result.put("obj", obj);
        result.put("flag", flag);
        result.put("code", response.getCode());
        result.put("subMsg", response.getSubMsg());
        result.put("isSuccess", response.isSuccess());
        result.put("subCode", response.getSubCode());
        return result;
    }

}
